package com.tongzhan.service;

import com.tongzhan.base.BaseCriteria;
import com.tongzhan.entity.SysDict;
import com.tongzhan.repository.SysDictRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 系统枚举配置
 * @author htmic
 * @date 2020/7/31
 */
@Service
public class SysDictService {

    @Autowired
    private SysDictRepository sysDictRepository;

    /**
     * 获取父类下的所有子数据
     * @param pcode
     * @return
     */
    public List<SysDict> getListByPcode(String pcode)  {
        SysDict pDict = sysDictRepository.findOne(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("code").is(pcode)));
        if (pDict != null) {
            List<SysDict> list = sysDictRepository.findAll(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("pid").is(pDict.getId())));
            return list;
        }
        return null;
    }

    /**
     * 获取父类下的所有子数据
     * @param pid
     * @return
     */
    public List<SysDict> getListByPid(String pid)  {
        SysDict pDict = sysDictRepository.findByPrimaryKey(pid);
        if (pDict != null) {
            List<SysDict> list = sysDictRepository.findAll(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("pid").is(pDict.getId())));
        }
        return null;
    }

    /**
     * 添加
     * @param sysDict
     */
    public long addDict(SysDict sysDict) {
        sysDict.setIsDelete(0);
        sysDict.setAddTime(new Date());

        long flag = sysDictRepository.insertSelective(sysDict);
        if (flag > 0) {
            return 1;
        }
        return 0;
    }

    /**
     * 获取枚举值的名称
     * @param pcode 上级的code
     * @param type
     * @return
     */
    public String getValueByType(String pcode, Integer type) {
        SysDict pDict = sysDictRepository.findOne(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("code").is(pcode)));
        if (pDict != null) {
            SysDict result = sysDictRepository.findOne(new Query().addCriteria(BaseCriteria.where("isDelete").is(0).and("pid").is(pDict.getId()).and("type").is(type + "")));
            if (result != null) {
                return result.getValue();
            }
        }
        return null;
    }
}
